package com.bnlr.lrparking.appui.mine.setting;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bumptech.glide.Glide;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.util.BitmapHelper;
import com.bnlr.lrparking.util.FileUtil;
import com.bnlr.lrparking.model.UpImgM;
import com.bnlr.lrparking.model.UploadGoodsBean;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.DbTOPxUtils;
import com.bnlr.lrparking.util.MyGridView;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.zzti.fengyongge.imagepicker.PhotoPreviewActivity;
import com.zzti.fengyongge.imagepicker.PhotoSelectorActivity;
import com.zzti.fengyongge.imagepicker.model.PhotoModel;
import com.zzti.fengyongge.imagepicker.util.CommonUtils;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 意见反馈
 * @author tian
 * @date 2018/3/27
 */

public class EditFankuiActivity extends BaseActivity {

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;

    @BindView(R.id.et_context)
    EditText etContext;
    @BindView(R.id.et_contact_phone)
    EditText etPhone;
    @BindView(R.id.gv_fankui_photo)
    MyGridView my_imgs_GV;
    private Unbinder unbinder;
    GridImgAdapter gridImgsAdapter;
    private List<PhotoModel> single_photos = new ArrayList<PhotoModel>();
    private ArrayList<UploadGoodsBean> img_uri = new ArrayList<UploadGoodsBean>();
    private int screen_widthOffset;
    private String path="";
    private List<String> urlArray= new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fankui);
        unbinder = ButterKnife.bind(this);
        tvNavTitle.setText("意见反馈");
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        screen_widthOffset = (display.getWidth() - (3* DbTOPxUtils.dip2px(this, 2)))/3;
        gridImgsAdapter = new GridImgAdapter();
        my_imgs_GV.setAdapter(gridImgsAdapter);
        if (img_uri.size() < 3) {
            img_uri.add(null);
        }
        gridImgsAdapter.notifyDataSetChanged();
    }

    @Override
    public void doClick(View v) {
        super.doClick(v);
        switch (v.getId()){
            case R.id.fankui_btn:
                if(TextUtils.isEmpty(etContext.getText().toString())){
                    CommonUtil.showToask(baseContext,"请输入投诉内容");
                }else{
                    SendFankui();
                }

                break;
            default:
                break;
        }
    }

    private void SendFankui() {

        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action","TouSuJianYi");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid",""));
            mRequest.add("txt",etContext.getText().toString());
            mRequest.add("phone",etPhone.getText().toString());
            String photoList = "";
            for (int i = 0; i < urlArray.size(); i++) {
                photoList = photoList + urlArray.get(i) +"|";
            }
            if (!TextUtils.isEmpty(photoList)) {
                photoList = photoList.substring(0, photoList.length() - 1);
            }
            mRequest.add("photoUrl",photoList);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<JSONObject>(baseContext, true, null) {
                        @Override
                        public void doWork(JSONObject data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (TextUtils.equals("1", code)) {
                                    startActivity(FankuiResultActivity.class);
                                    finish();
                                } else {
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }
    class GridImgAdapter extends BaseAdapter implements ListAdapter {
        @Override
        public int getCount() {
            return img_uri.size();
        }
        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(EditFankuiActivity.this).inflate(R.layout.activity_addstory_img_item, null);
            EditFankuiActivity.GridImgAdapter.ViewHolder holder;
            if(convertView!=null){
                holder = new EditFankuiActivity.GridImgAdapter.ViewHolder();
                convertView = LayoutInflater.from(EditFankuiActivity.this).inflate(R.layout.activity_addstory_img_item,null);
                convertView.setTag(holder);
            }else{
                holder = (EditFankuiActivity.GridImgAdapter.ViewHolder) convertView.getTag();
            }
            holder.add_IB = (ImageView) convertView.findViewById(R.id.add_IB);
            holder.delete_IV = (ImageView) convertView.findViewById(R.id.delete_IV);
            AbsListView.LayoutParams param = new AbsListView.LayoutParams(screen_widthOffset, screen_widthOffset);
            convertView.setLayoutParams(param);
            if (img_uri.get(position) == null) {
                holder.delete_IV.setVisibility(View.GONE);
                holder.add_IB.setImageResource(R.mipmap.addimg);
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(EditFankuiActivity
                                .this, PhotoSelectorActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        intent.putExtra("limit", 3 - (img_uri.size() - 1));
                        startActivityForResult(intent, 0);
                    }
                });
            } else {
                Glide.with(EditFankuiActivity.this).load(img_uri.get(position).getUrl()).into(holder.add_IB);
                holder.add_IB.setImageResource(R.mipmap.addimg);
                holder.delete_IV.setOnClickListener(new View.OnClickListener() {
                    private boolean is_addNull;
                    @Override
                    public void onClick(View arg0) {
                        is_addNull = true;
                        img_uri.remove(position);
                        urlArray.remove(position);
                        single_photos.remove(position);
                        for (int i = 0; i < img_uri.size(); i++) {
                            if (img_uri.get(i) == null) {
                                is_addNull = false;
                                continue;
                            }
                        }
                        if (is_addNull) {
                            img_uri.add(null);
                        }
                        //FileUtils.DeleteFolder(img_url);//删除在emulate/0文件夹生成的图片
                        gridImgsAdapter.notifyDataSetChanged();
                    }
                });
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("photos",(Serializable)single_photos);
                        bundle.putInt("position", position);
                        bundle.putBoolean("isSave",false);
                        bundle.putBoolean("isNet",true);
                        CommonUtils.launchActivity(EditFankuiActivity.this, PhotoPreviewActivity.class, bundle);
                    }
                });

            }
            return convertView;
        }
        class ViewHolder {
            ImageView add_IB;
            ImageView delete_IV;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");
                    if (img_uri.size() > 0) {
                        img_uri.remove(img_uri.size() - 1);
                    }
                    for (int i = 0; i < paths.size(); i++) {
                        if (FileUtil.fileExists(paths.get(i))) {
                            img_uri.add(new UploadGoodsBean(paths.get(i), false));
                            //上传参数
                            path = path + CommonUtil.bitmapToBase64(BitmapHelper.getImage(paths.get(i), 200))
                                    + "|";
                        }
                    }
                    if (path.length() > 0) {
                        path = path.substring(0, path.length() - 1);
                        sendImage(path, "2");//上传图片
                        if (img_uri.size() < 3) {
                            img_uri.add(null);
                        }
                        gridImgsAdapter.notifyDataSetChanged();
                    }
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void sendImage(String img,String stallType){
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP_UpImg, LrConstant.POST);
            mRequest.add("action", "FileUploadImage");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("type", stallType);
            mRequest.add("img", img);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<UpImgM>(baseContext, true, null) {
                        @Override
                        public void doWork(UpImgM data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (TextUtils.equals("1", code)) {
                                    String url = obj.getString("data");
                                    String[] arr = url.split(",");
                                    for (int i = 0; i < arr.length; i++) {
                                        urlArray.add(arr[i]);
                                    }
                                    for (int i = 0; i < urlArray.size(); i++) {
                                        PhotoModel photoModel = new PhotoModel();
                                        photoModel.setOriginalPath(urlArray.get(i));
                                        photoModel.setChecked(true);
                                        single_photos.add(photoModel);
                                    }
                                    path = "";
                                } else {
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }
}
